const gulp = require('gulp');
const uglify = require('gulp-uglify');
const htmlmin = require('vispa-htmlmin');
const gulpscss = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const cssmin = require('gulp-cssmin');
const rename = require('gulp-rename');
const del = require('del');
const babel = require('gulp-babel');
const imagemin = require('gulp-imagemin')
const watch = require('gulp-watch');
const browserSync = require('browser-sync').create();
const webserver = require('gulp-webserver');
const { src } = require('gulp');
// html压缩
const htmlHandler = function() {
    return gulp
        .src('./src/html/*.html')
        .pipe(htmlmin())
        .pipe(gulp.dest('dist/html/'))
};
// css转码压缩
const cssHandler = function() {
    return gulp
        .src('./src/scss/*.scss')
        .pipe(gulpscss())
        .pipe(autoprefixer("last 3 version", "safari 5", "ie 8", "ie 9"))
        .pipe(cssmin())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('dist/css/'));
};
// js转义压缩
const jsHandler = function() {
    return gulp
        .src('./src/js/*.js')
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('dist/js/'));
};
// 图片压缩
const imgHandler = function() {
    return gulp.src('./src/static/*.*')
        .pipe(imagemin({
            progressive: true
        }))
        .pipe(gulp.dest('dist/images'));
};
// 删除文件
const clean = function() {
    return del(['dist']);
};
// 启动服务器
const webHandler = function() {
    return gulp
        .src('./dist/')
        .pipe(webserver({
            host: 'www.shizai.com',
            port: '8080',
            livereload: true,
            open: './html/index.html',
            proxies: [{ //代理
                source: "api/",
                target: "www.baidu.com"
            }]
        }))
};


// 监听函数文件改变编译

const watchHander = function() {
    gulp.watch('./src/html/*.html', htmlHandler);
    gulp.watch('./src/scss/*.scss', cssHandler);
    gulp.watch('./src/js/*.js', jsHandler);
}

module.exports.default = gulp.series(
    clean,
    gulp.parallel(htmlHandler, cssHandler, jsHandler, imgHandler),
    webHandler,
    watchHander
);